package ar.fiuba.logger;

import java.io.File;

import ar.fiuba.logger.configfile.LogConfigPropertiesFile;
import ar.fiuba.logger.configfile.LogConfigXmlFile;

/**
 * The Class LoggerBuilder.
 * 
 * This class applies configuration rules when creating a Logger object.
 */
public class LoggerBuilder {

  /** The Constant defaultPropertiesConfigFileName. */
  private static final String defaultPropertiesConfigFileName = "./logger-config.properties";

  /** The Constant defaultXMLConfigFileName. */
  private static final String defaultXMLConfigFileName = "./logger-config.xml";

  /**
   * Builds the.
   *
   * @param name the name
   * @return the logger
   */
  public static Logger build(String name) {
    LogConfigReader reader;
    LogConfig config;

    if (LoggerBuilder.fileExists(defaultPropertiesConfigFileName)) {
      reader = new LogConfigPropertiesFile(defaultPropertiesConfigFileName);
      config = reader.read();
    } else {
      if (LoggerBuilder.fileExists(defaultXMLConfigFileName)) {
        reader = new LogConfigXmlFile(defaultXMLConfigFileName);
        config = reader.read();
      } else {
        // We could set the default config in here instead of doing it at LogConfig
        config = new LogConfig();
      }
    }

    return new Logger(name, config);
  }

  /**
   * Builds the.
   *
   * @param name the name
   * @param config the config
   * @return the logger
   */
  public static Logger build(String name, LogConfig config) {
    return new Logger(name, config);
  }

  /**
   * Builds the from properties.
   *
   * @param name the name
   * @param configFile the config file
   * @return the logger
   */
  public static Logger buildFromProperties(String name, String configFile) {
    LogConfigReader reader = new LogConfigPropertiesFile(configFile);
    LogConfig config = reader.read();

    return new Logger(name, config);
  }

  /**
   * Builds the from xml.
   *
   * @param name the name
   * @param configFile the config file
   * @return the logger
   */
  public static Logger buildFromXML(String name, String configFile) {
    LogConfigReader reader = new LogConfigXmlFile(configFile);
    LogConfig config = reader.read();

    return new Logger(name, config);
  }

  /**
   * File exists.
   *
   * @param filename the filename
   * @return the boolean
   */
  private static Boolean fileExists(String filename) {
    File file = new File(filename);

    return file.exists() && file.isFile();
  }
}
